package com.shenmazong.label.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shenmazong.label.entity.TbTaskLabel;
import com.shenmazong.label.entity.TbTaskLabelType;
import com.shenmazong.label.mapper.TbTaskLabelTypeMapper;
import com.shenmazong.label.service.TaskLabelService;
import com.shenmazong.label.mapper.TbTaskLabelMapper;
import com.shenmazong.util.ChooseIsNull;
import com.shenmazong.utils.ResultResponse;
import com.shenmazong.vo.AllTaskLabelVo;
import com.shenmazong.vo.BatchChooseIdVo;
import com.shenmazong.vo.LabelVo;
import com.shenmazong.vo.ListParamVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 *serviceImpl Qi
 */
@Service
public class TaskLabelServiceImpl extends ServiceImpl<TbTaskLabelMapper, TbTaskLabel>
    implements TaskLabelService {

    @Autowired
    private  TbTaskLabelMapper  labelMapper;
    @Autowired
    private TbTaskLabelTypeMapper labelTypeMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResultResponse saveTaskLabel(TbTaskLabel tbTaskLabel) {
        int i = labelMapper.insert(tbTaskLabel);
        if(i<1){
            return ResultResponse.FAILED("新增失败");
        }
        return ResultResponse.SUCCESS(labelMapper.selectById(tbTaskLabel.getLabelId()));
    }

    @Override
    public ResultResponse deleteTaskLabel(BatchChooseIdVo chooseIdVo) {
        if (ChooseIsNull.idsIsNull(chooseIdVo)){
            return ResultResponse.FAILED("未选择要删除的数据");
        }
        int i = labelMapper.deleteBatchIds(chooseIdVo.getIds());
        if(i<1){
            return ResultResponse.FAILED("删除失败");
        }
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse updateTaskLabel(TbTaskLabel tbTaskLabel) {
        int i = labelMapper.updateById(tbTaskLabel);
        if(i<1){
            return ResultResponse.FAILED("修改失败");
        }
        return ResultResponse.SUCCESS(labelMapper.selectById(tbTaskLabel.getLabelId()));
    }

    @Override
    public ResultResponse listTaskLabel(ListParamVo paramVo) {
        //非空判断
        if(paramVo.getParamMap().size()==0 || paramVo.getParamMap().get("schoolId")==null){
            return ResultResponse.FAILED("无效查询条件");
        }
        //分页
        IPage<TbTaskLabel> page = new Page<>(paramVo.getCurrent(), paramVo.getSize());

        //标签名称 标签类型 空处理
        if(StringUtils.checkValNull(paramVo.getParamMap().get("labelName"))){
            paramVo.getParamMap().put("labelName","");
        }
        if(StringUtils.checkValNull(paramVo.getParamMap().get("labelTypeId"))){
            paramVo.getParamMap().put("labelTypeId","");
        }

        //列表
        IPage<LabelVo> selectPage = labelMapper.listTaskLabel(page, paramVo.getParamMap().get("schoolId"),
                paramVo.getParamMap().get("labelName"),paramVo.getParamMap().get("labelTypeId"));
        return ResultResponse.SUCCESS(selectPage);
    }

    @Override
    public ResultResponse saveTaskLabelType(TbTaskLabelType taskLabelType) {
        int i = labelTypeMapper.insert(taskLabelType);
        if(i<1){
            return ResultResponse.FAILED("新增失败");
        }
        return ResultResponse.SUCCESS(labelTypeMapper.selectById(taskLabelType.getLabelTypeId()));
    }

    @Override
    public ResultResponse deleteTaskLabelType(BatchChooseIdVo chooseIdVo) {
        if (ChooseIsNull.idsIsNull(chooseIdVo)){
            return ResultResponse.FAILED("未选择要删除的数据");
        }
        int i = labelTypeMapper.deleteBatchIds(chooseIdVo.getIds());
        if(i<1){
            return ResultResponse.FAILED("删除失败");
        }
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse updateTaskLabelType(TbTaskLabelType taskLabelType) {
        int i = labelTypeMapper.updateById(taskLabelType);
        if(i<1){
            return ResultResponse.FAILED("修改失败");
        }
        return ResultResponse.SUCCESS(labelTypeMapper.selectById(taskLabelType.getLabelTypeId()));
    }

    @Override
    public ResultResponse listAllTaskLabelType() {
        return ResultResponse.SUCCESS(labelTypeMapper.selectList(null));
    }

    @Override
    public ResultResponse listAllTaskLabel(TbTaskLabel taskLabel) {
        //非空判断
        if(taskLabel== null || StringUtils.checkValNull(taskLabel.getSchoolId())){
            return ResultResponse.FAILED("无效查询条件");
        }

        //生成Redis中的key
        String key = "task_label_"+taskLabel.getSchoolId();
        ObjectMapper mapper = new ObjectMapper();

        //判断Redis中是否存在
        if(redisTemplate.hasKey(key)){
            try {
                String content = redisTemplate.opsForValue().get(key);
                List<AllTaskLabelVo> list = mapper.readValue(content, new TypeReference<List<AllTaskLabelVo>>() {
                });
                return ResultResponse.SUCCESS(list);
            } catch (Exception e) {
                e.printStackTrace();
                return getListAllTaskLabelBySQL(taskLabel);
            }
        }else {
            return getListAllTaskLabelBySQL(taskLabel);
        }

    }

    public ResultResponse getListAllTaskLabelBySQL(TbTaskLabel taskLabel){
        //获取类型列表
        List<TbTaskLabelType> typeList = labelTypeMapper.selectList(
                new QueryWrapper<TbTaskLabelType>().lambda().eq(TbTaskLabelType::getSchoolId, taskLabel.getSchoolId())
        );

        List<AllTaskLabelVo> list = new ArrayList<>();
        for (TbTaskLabelType type : typeList) {
            //第一层数据
            AllTaskLabelVo allTaskLabelVo = new AllTaskLabelVo();
            allTaskLabelVo.setValue(type.getLabelTypeId());
            allTaskLabelVo.setLabel(type.getLabelTypeName());

            //获取第二层数据 根据类型
            List<TbTaskLabel> labelList = labelMapper.selectList(
                    new QueryWrapper<TbTaskLabel>().lambda().eq(TbTaskLabel::getLabelTypeId, type.getLabelTypeId())
            );
            List<AllTaskLabelVo> list2 = new ArrayList<>();
            for (TbTaskLabel label : labelList) {
                AllTaskLabelVo allTaskLabelVo2 = new AllTaskLabelVo();
                allTaskLabelVo2.setValue(label.getLabelId());
                allTaskLabelVo2.setLabel(label.getLabelName());
                list2.add(allTaskLabelVo2);
            }
            allTaskLabelVo.setChildren(list2);

            list.add(allTaskLabelVo);
        }

        //存入Redis
        //生成Redis中的key
        String key = "task_label_"+taskLabel.getSchoolId();
        ObjectMapper mapper = new ObjectMapper();
        try {
            String value = mapper.writeValueAsString(list);
            redisTemplate.opsForValue().set(key,value,1, TimeUnit.DAYS);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return ResultResponse.SUCCESS(list);
    }
}




